package cn.basic.auth.controller;

import cn.basic.auth.dto.LoginDTO;
import cn.basic.auth.service.ILoginService;
import cn.basic.utils.AjaxResult;
import cn.basic.utils.BasicMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @description:
 * 登录控制器
 * @date: 2023/3/7 11:25
 * @author: ZhaoLc
 * @version: 1.0
 */
@RestController
public class LoginController {

    @Resource
    ILoginService loginService;

    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public AjaxResult login(@RequestBody LoginDTO loginDTO){
        try {
            Map<String,Object> map = loginService.login(loginDTO);
            return AjaxResult.me().setObject(map).setMessage("登录成功！");
        } catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
        }
    }

    @RequestMapping(value = "/logout",method = RequestMethod.POST)
    public AjaxResult logout(HttpServletRequest request){
        try {
            String token = request.getHeader("token");
            BasicMap.loginMap.remove(token);
            return AjaxResult.me().setMessage(null);
        } catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
        }
    }
}
